package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.live.activity.R;
import com.live.adapter.LiveVideoSA;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveVideo extends AsyncTask<Bundle, Integer, String> {

	private LiveVideoSA adapter;

	private List<Map<String, Object>> liveVideoList;

	private List<Map<String, Object>> liveVideoListTemp;

	private Context context = null;

	private String locale = LiveTools.getLocaleLanguage();

	private Dialog proDialog = null;

	public LiveVideo(Context context, List<Map<String, Object>> liveVideoList, LiveVideoSA adapter) {
		this.context = context;
		this.liveVideoList = liveVideoList;
		this.adapter = adapter;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());

		proDialog = new Dialog(context, R.style.progress_dialog);
		proDialog.setContentView(R.layout.live_progress_dialog);
		proDialog.show();
	}

	@Override
	protected String doInBackground(Bundle... params) {

		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		String matchTime = params[0].getString("matchTime").substring(0, 10);
		String homeTeam = params[0].getString("homeTeamName");
		String visitTeam = params[0].getString("visitTeamName");
		String url = Constant.SITE_URL + "live_video.php?locale=" + LiveTools.getLocaleLanguage();
		try {
			if ("2".equals(params[0].getString("matchCategory"))) {
				url += "&matchTime=" + matchTime + "&videoCategory=2";
				url += "&homeTeam=" + URLEncoder.encode(visitTeam, "UTF-8") + "&visitTeam="
						+ URLEncoder.encode(homeTeam, "UTF-8");
			} else if ("3".equals(params[0].getString("matchCategory"))) {
				url += "&matchTime=" + matchTime + "&videoCategory=3";
				url += "&homeTeam=" + URLEncoder.encode(visitTeam, "UTF-8") + "&visitTeam="
						+ URLEncoder.encode(homeTeam, "UTF-8");
			} else {
				url += "&matchTime=" + matchTime + "&videoCategory=0";
				url += "&homeTeam=" + URLEncoder.encode(homeTeam, "UTF-8") + "&visitTeam="
						+ URLEncoder.encode(visitTeam, "UTF-8");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		liveVideoListTemp = getServerData(url);
		if (liveVideoList.size() != liveVideoListTemp.size()) {
			// 初始化list
			for (int i = liveVideoList.size() - 1; i >= 0; i--) {
				liveVideoList.remove(i);
			}
			liveVideoList.addAll(liveVideoListTemp);
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		proDialog.dismiss();
		adapter.notifyDataSetChanged();
	}

	public List<Map<String, Object>> getServerData(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray video = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < video.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("videoId", video.getJSONObject(i).get("videoId"));
								map.put("videoTitle", LiveTools.tradToSimp(video.getJSONObject(i).get("videoTitle")
										.toString(), locale));
								map.put("videoImgUrl", video.getJSONObject(i).get("videoImgUrl"));
								map.put("videoLength", video.getJSONObject(i).get("videoLength"));
								map.put("videoUrl", video.getJSONObject(i).get("videoUrl"));
								map.put("videoWatch", video.getJSONObject(i).get("videoWatch"));
								map.put("videoTime", video.getJSONObject(i).get("updateDate"));
								map.put("videoCategory", video.getJSONObject(i).get("videoCategory"));
								data.add(map);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "远程服务器无响应，请稍候再试！", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return data;
	}
}